package icu.xuyijie.springbootlearning2.chapter3.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2025/02/24 15:56
 * @description 演示操作数据库
 */
@RestController
@RequestMapping("/jdbc")
public class JdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/query")
    public List<MyEntity> query() {
        RowMapper<MyEntity> rowMapper = new BeanPropertyRowMapper<>(MyEntity.class);
        List<MyEntity> list = jdbcTemplate.query("select * from test", rowMapper);
        System.out.println(list);
        return list;
    }

    @RequestMapping("/add")
    public void add() {
        String sql = "INSERT INTO test (name, create_time) VALUES (?, ?)";
        jdbcTemplate.update(sql, "xyj", new Date());
    }

    @RequestMapping("/update")
    public void update() {
        String sql = "UPDATE test SET name = ? WHERE id = ?";
        jdbcTemplate.update(sql, "asdasdasdas", 1);
    }

    @RequestMapping("/del")
    public void del() {
        String sql = "DELETE FROM test WHERE id = ?";
        jdbcTemplate.update(sql, 2);
    }

}
